import json
from urllib import parse, request
import time


## 此函数用于获取access_token，不知道有啥作用，参考微信公众号开发文档：https://developers.weixin.qq.com/doc/offiaccount/Basic_Information/Get_access_token.html

# // 获取token
def get_wxCode_token():
    try:
        appid = "你自己的appid"
        secret = "你自己的secret"
        textmod = {"grant_type": "client_credential",
            "appid": appid,
            "secret": secret
        }
        textmod = parse.urlencode(textmod)
        header_dict = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36'}
        url = 'https://api.weixin.qq.com/cgi-bin/token'
        req = request.Request(url='%s%s%s' % (url, '?', textmod), headers=header_dict)
        res = request.urlopen(req)
        res = res.read().decode(encoding='utf-8')
        res = json.loads(res)
        access_token = res["access_token"]
        print('access_token:',(access_token,time.time()))
        return (access_token,time.time())
    except Exception as e:
        print(e)
        return False


if __name__ == '__main__':
    # 注意，获取不到access_token，很可能你没有在公众号上添加 你的ip地址 为白名单
    get_wxCode_token()

